package com.dgut.ibeacon.controller;

import com.dgut.ibeacon.entity.Role;
import com.dgut.ibeacon.entity.User;
import com.dgut.ibeacon.service.IRoleService;
import com.dgut.ibeacon.service.IUserService;
import com.dgut.ibeacon.utils.ShiroUtils;
import com.dgut.ibeacon.utils.core.ServletUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
public class IndexController {

    @Autowired
    IUserService userService;

    @Autowired
    IRoleService roleService;

    @GetMapping("/index")
    public String indexPage(HttpServletRequest request, HttpServletResponse response, HttpSession session)
    {
        User user= ShiroUtils.getSysUser();
        Role userRole=roleService.getById(user.getUserId());
        Role role=roleService.getById(userRole.getUserId());
        session.setAttribute("user", user);
        session.setAttribute("role",role);
        return "index";
    }

    @GetMapping({"/login","/"})
    public String loginPage(HttpServletRequest request, HttpServletResponse response)
    {
        // 如果是Ajax请求，返回Json字符串。
        if (ServletUtils.isAjaxRequest(request))
        {
            return ServletUtils.renderString(response, "{\"code\":\"1\",\"msg\":\"未登录或登录超时。请重新登录\"}");
        }
        //登录成功跳转首页
        if(ShiroUtils.getSubject().isAuthenticated()==true){
            return "index";
        }
        //否则返回登录页
        return "login";
    }

    @GetMapping("/register")
    public String register(){
        return "register";
    }

}
